package ch1001;

public class SyncTicket {
    public static void main(String[] args) {
        TicketWindow ticketWindow=new TicketWindow();
        Thread thread01=new Thread(ticketWindow,"窗口01");
        Thread thread02=new Thread(ticketWindow,"窗口02");
        Thread thread03=new Thread(ticketWindow,"窗口03");
        Thread thread04=new Thread(ticketWindow,"窗口04");
        thread01.start();
        thread02.start();
        thread03.start();
        thread04.start();
    }
}

class TicketWindow implements Runnable{
    private int ticket=10;

    public void run(){
        while (getTicket()){//<---就比如这里，他就是锁
            try {
                Thread.sleep(1000);
            }catch (InterruptedException e){
                e.getStackTrace();
            }
        }
    }
    private synchronized boolean getTicket(){//也可以不要申请lock直接加前缀,那么锁是谁呢？this！谁用我谁就是锁！
         //上锁，锁部分线程不能同时执行！
            if (ticket>0){
                System.out.println(Thread.currentThread().getName()+"卖出票为"+ticket--);
                return true;
            }
            else{
                return false;
            }
    }
}
